#!/usr/bin/env python
# -*- coding:utf-8 -*-

from json import loads
from re import search,I
from os import path,listdir,sep
from lib.utils.params import *
from lib.utils.printer import *
from lib.utils.readfile import *
from lib.request.request import *
from lib.utils.payload import *
from lib.utils.settings import SQLDBERRORS_PATH

class headersqli(Request):
    """
    对HTTP的头信息header,检测是否可能存在sql注入漏洞
    """
    get = "GET"
    def __init__(self,kwargs,url,data):
        Request.__init__(self,kwargs)
        self.url = url
        self.data = data
        self.result = {
            'headersqli':None
        }
    def search(self,resp,content):
        for error in content['db']['regexp']:
            if search(error,resp):
                _ = content['db']['name']
                return _
    def serror(self,resp):
        _ = None
        realpath = SQLDBERRORS_PATH
        for f in listdir(realpath):
            abspath = realpath + sep + f
            _ = self.search(resp,loads(readfile(abspath)[0],encoding="utf-8"))
            if _ != None : return _
    def cookie(self):
        DB = None
        URL = None
        DATA = None
        PAYLOAD = None
        for payload in sql():
            headers = {
                'Cookie':'{}'.format(payload)
            }
            more("检测载荷[cookie]:{},{}".format(self.url,headers['Cookie']))
            req = self.Send(url=self.url,method=self.get,headers=headers)
            error = self.serror(req.content)
            if error:
                DB = error
                URL = req.url
                PAYLOAD = payload
                break
        if URL and PAYLOAD:
            plus("疑似Cookie头信息存在SQL注入漏洞:")
            more("URL[地址]: {}".format(URL))
            more("PAYLOAD[有效载荷]: {}".format(PAYLOAD))
            more("DBMS[数据库]: {}".format(DB))
            if self.result['headersqli']:
                self.result['headersqli'] = "[cookie],{},{}".format(DB,PAYLOAD)
            else:
                self.result['headersqli'] += " [cookie],{},{}".format(DB,PAYLOAD)
        else:
            info_nothing()
    def referer(self):
        DB = None
        URL = None
        DATA = None
        PAYLOAD = None
        for payload in sql():
            headers = {
                'Referer':'{}'.format(payload)
            }
            more("检测载荷[Referer]:{},{}".format(self.url,headers['Referer']))
            req = self.Send(url=self.url,method=self.get,headers=headers)
            error = self.serror(req.content)
            if error:
                DB = error
                URL = req.url
                PAYLOAD = payload
                break
        if URL and PAYLOAD:
            plus("疑似Referer头信息存在sql注入漏洞:")
            more("URL: {}".format(URL))
            more("PAYLOAD: {}".format(PAYLOAD))
            more("DBMS: {}".format(DB))
            if self.result['headersqli']:
                self.result['headersqli'] = "[referer],{},{}".format(DB,PAYLOAD)
            else:
                self.result['headersqli'] += " [referer],{},{}".format(DB,PAYLOAD)
        else:
            info_nothing()
    def useragent(self):
        DB = None
        URL = None
        DATA = None
        PAYLOAD = None
        for payload in sql():
            headers = {
                'User-Agent':'{}'.format(payload)
            }
            more("检测载荷[User-Agent]:{},{}".format(self.url,headers['User-Agent']))
            req = self.Send(url=self.url,method=self.get,headers=headers)
            error = self.serror(req.content)
            if error:
                DB = error
                URL = req.url
                PAYLOAD = payload
                break
        if URL and PAYLOAD:
            plus("疑似UserAgnet头信息存在sql注入漏洞::")
            more("URL[地址]: {}".format(URL))
            more("PAYLOAD[有效载荷]: {}".format(PAYLOAD))
            more("DBMS[数据库]: {}".format(DB))
            if self.result['headersqli']:
                self.result['headersqli'] = "[useragent],{},{}".format(DB,PAYLOAD)
            else:
                self.result['headersqli'] += " [useragent],{},{}".format(DB,PAYLOAD)
        else:
            info_nothing()
    def check(self):
        info('检测HTTP头信息[Cookie,Referer,UserAgent]SQL注入漏洞...')
        self.cookie()
        self.referer()
        self.useragent()
        return self.result
def run(kwargs,url,data):
    result = {}
    scan = headersqli(kwargs,url,data)
    result = scan.check()
    return result